package com.example.shop_2212.fg

import androidx.recyclerview.widget.LinearLayoutManager
import com.example.base.mvvm.BaseFragment
import com.example.base.net.Const
import com.example.shop_2212.R
import com.example.shop_2212.adapter.OneAdapter
import com.example.shop_2212.adapter.TwoAdapter
import com.example.shop_2212.databinding.FragmentCategoryBinding
import com.example.shop_2212.fgviewmodel.CategoryViewModel


class CategoryFragment : BaseFragment<FragmentCategoryBinding,CategoryViewModel>() {
    lateinit var oneAdapter: OneAdapter
    lateinit var twoAdapter: TwoAdapter
    var flag = false//记录右侧滑动是人为的，还是因为左侧点击引起的  //为false时是人为滑动
    override fun getLayout(): Int = R.layout.fragment_category

    override fun getViewModel(): Class<CategoryViewModel>  = CategoryViewModel::class.java

    override fun initView() {
        oneAdapter = OneAdapter()
        binding.rvOne.adapter = oneAdapter
        binding.rvOne.layoutManager = LinearLayoutManager(context)

        twoAdapter = TwoAdapter()
        binding.rvTwo.adapter = twoAdapter
        val layoutManager = LinearLayoutManager(context)
        binding.rvTwo.layoutManager = layoutManager

        viewModel.category()
        //点击左侧rv，右侧rv指定地方置顶
        oneAdapter.setOnItemClickListener { adapter, view, position ->
            oneAdapter.setType(oneAdapter.data[position].id)
            //右侧要滑动
            flag = true//左侧点击引起的
            layoutManager.scrollToPositionWithOffset(position,0)
            flag = false//左侧点击引起的滑动结束了
        }
        //滑动右侧rv,左侧置顶rv选中
        binding.rvTwo.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            val itemPosition = layoutManager.findFirstVisibleItemPosition()//显示的第一个下标
            if (!flag) {
                if (twoAdapter.data[itemPosition].id != oneAdapter.selectType) {//只有不相同的时候，左侧rv才发生变化
                    oneAdapter.setType(twoAdapter.data[itemPosition].id)//将当前的数据显示为红色的
                    binding.rvOne.scrollToPosition(itemPosition)
                }
            }
        }
    }

    override fun initData() {
        viewModel.categorySuccess.observe(this){
            if(it.code==Const.RESULT_OK){
                oneAdapter.data.clear()
                oneAdapter.data.addAll(it.data)
                oneAdapter.notifyDataSetChanged()

                twoAdapter.data.clear()
                twoAdapter.data.addAll(it.data)
                twoAdapter.notifyDataSetChanged()
            }
        }
    }

}